package cn.nzcong.jpress.addon.articlesync.controller;

import cn.nzcong.jpress.addon.articlesync.annotation.SecondStep;
import cn.nzcong.jpress.addon.articlesync.common.Constant;
import cn.nzcong.jpress.addon.articlesync.common.Exception.AuthException;
import cn.nzcong.jpress.addon.articlesync.common.Exception.BaseException;
import cn.nzcong.jpress.addon.articlesync.common.util.HttpUtil;
import cn.nzcong.jpress.addon.articlesync.platform.BasePlatform;
import cn.nzcong.jpress.addon.articlesync.platform.PlatformHolder;
import cn.nzcong.jpress.addon.articlesync.service.impl.ConfigOptionService;
import cn.nzcong.jpress.addon.articlesync.vo.PlatformVerifyVo;
import cn.nzcong.jpress.addon.articlesync.vo.config.SecondStepConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import io.jboot.web.controller.annotation.RequestMapping;
import io.jpress.JPressConsts;
import io.jpress.core.menu.annotation.AdminMenu;
import io.jpress.model.User;
import io.jpress.module.article.model.Article;
import io.jpress.module.article.service.ArticleService;
import io.jpress.web.base.AdminControllerBase;
import io.jpress.web.interceptor.AdminInterceptor;
import io.jpress.web.interceptor.CSRFInterceptor;
import io.jpress.web.interceptor.PermissionInterceptor;
import io.jpress.web.interceptor.UserInterceptor;
import jdk.nashorn.api.scripting.URLReader;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;


@RequestMapping(value = "/admin/articlesync",viewPath = "/")
@Before({
        CSRFInterceptor.class,
        AdminInterceptor.class,
        UserInterceptor.class,
        PermissionInterceptor.class,
})
public class ArticleSyncAddonController extends AdminControllerBase {

    @Inject
    private ArticleService articleService;
    @Inject
    private ConfigOptionService configOptionService;

    public void getConfig() {
        try{
            // 查询两步验证配置
            SecondStepConfig ssConfig = configOptionService.getSecondStepConfig();
            User user = super.getLoginedUser();
            JSONObject result = new JSONObject();
            result.put("ssaEnable", ssConfig != null && ssConfig.isEnable());
            result.put("userName", user.getUsername());
            result.put("nickname", user.getNickname());
            result.put("avatar", user.getAvatar());
            renderJson(Ret.ok("config", result));
        } catch (BaseException e){
            renderJson(Ret.fail("message", "保存失败 - " + e.getMessage()));
        } catch (Throwable e){
            renderJson(Ret.fail("message", "内部错误 - " + e.getMessage()));
        }
    }

    public void getPlatforms(){
        try{
            // 验证所有开启的平台配置
            List<PlatformVerifyVo> verifyVoList = new ArrayList<>();
            for(BasePlatform platform : PlatformHolder.getAllPlatform()){
                PlatformVerifyVo verify = platform.verifyConf();
                verifyVoList.add(verify);
            }
            renderJson(Ret.ok("platforms", verifyVoList));
        } catch (BaseException e){
            renderJson(Ret.fail("message", "保存失败 - " + e.getMessage()));
        } catch (Throwable e){
            renderJson(Ret.fail("message", "内部错误 - " + e.getMessage()));
        }
    }

    @SecondStep
    public void configPage() {
        SecondStepConfig ssConfig = configOptionService.getSecondStepConfig();
        setAttr("ssaEnable", ssConfig != null && ssConfig.isEnable());
        for(BasePlatform platform : PlatformHolder.getAllPlatform()){
            JSONObject confObj = (JSONObject) JSON.toJSON(platform.getConfigObj());
            confObj.put("displayName", platform.getPlatformEnum().getDisplayName());
            setAttr(platform.getPlatformEnum().getName(), confObj);
        }
        render("articlesync/config.html");
    }

    @AdminMenu(groupId = JPressConsts.SYSTEM_MENU_ADDON, text = "文章同步")
    public void listPage() {
        /**
         * 文章查询处理
         */
        String status = getPara("status");
        String title = getPara("title");
        Long categoryId = getParaToLong("categoryId");
        Properties properties = getMasterAddonInfo();
        Page<Article> page =
                StringUtils.isBlank(status)
                        ? articleService._paginateWithoutTrash(getPagePara(), 10, title, categoryId)
                        : articleService._paginateByStatus(getPagePara(), 10, title, categoryId, status);
        setAttr("page", page);
        Long draftCount = articleService.findCountByStatus(Article.STATUS_DRAFT);
        Long trashCount = articleService.findCountByStatus(Article.STATUS_TRASH);
        Long normalCount = articleService.findCountByStatus(Article.STATUS_NORMAL);
        setAttr("draftCount", draftCount);
        setAttr("trashCount", trashCount);
        setAttr("normalCount", normalCount);
        setAttr("totalCount", draftCount + trashCount + normalCount);

        String masterVer = properties.getProperty("version");
        setAttr("newVer", masterVer);
        setAttr("hasNew", !StringUtils.isBlank(Constant.ADDON_VER) && !StringUtils.isBlank(masterVer) && !Constant.ADDON_VER.equalsIgnoreCase(masterVer));
        setAttr("updateUrl", Constant.AUTHOR_WEBSITE);
        /**
         * 账号验证结果处理
         */
        List<JSONObject> platformList = new ArrayList<>();
        boolean allRight = true;
        for(BasePlatform platformItem : PlatformHolder.getEnablePlatform()){
            StringBuffer msg = new StringBuffer();
            PlatformVerifyVo verifyVo = platformItem.verifyConf();
            if(!verifyVo.isValid()){
                allRight = false;
                msg.append(verifyVo.getReason());
            }
            JSONObject platform = new JSONObject();
            platform.put("name", platformItem.getPlatformEnum().getName());
            platform.put("displayName", platformItem.getPlatformEnum().getDisplayName());
            platform.put("enable", platformItem.enable());
            platform.put("verify", verifyVo.isValid());
            platform.put("msg", msg.toString());
            platformList.add(platform);
        }
        setAttr("platformList", platformList);
        setAttr("verifyAllRight", allRight);

        // 返回到页面
        render("articlesync/list.html");
    }

    @SecondStep
    @Clear(CSRFInterceptor.class)
    public void doConfig(){
        try{
            String platform = getAttr("platform");
            String confJson = JSON.toJSONString(getAttr("conf"));
            BasePlatform platformObj = PlatformHolder.getByName(platform);
            platformObj.saveConf(platformObj.parseConfig(confJson));
            renderJson(Ret.ok("message", "保存成功"));
        } catch (BaseException e){
            renderJson(Ret.fail("message", "保存失败 - " + e.getMessage()));
        } catch (Throwable e){
            renderJson(Ret.fail("message", "内部错误 - " + e.getMessage()));
        }
    }

    @SecondStep
    public void doPublish(){
        try{
            String platform = getAttr("platform");
            Long articleId = Long.valueOf(getAttr("articleId"));
            String domain = getAttrForStr("domain");
            PlatformHolder.getByName(platform).doPublishArticle(articleId, domain);
            renderJson(Ret.ok("message", "发布成功"));
        } catch (BaseException e){
            renderJson(Ret.fail("message", "发布失败 - " + e.getMessage()));
        } catch (Throwable e){
            renderJson(Ret.fail("message", "内部错误 - " + e.getMessage()));
        }
    }

    public void doVerify(){
        try{
            String platform = getAttr("platform");
            String confJson = JSONObject.toJSONString(getAttr("conf"));
            BasePlatform platformObj = PlatformHolder.getByName(platform);
            PlatformVerifyVo verifyVo = platformObj.doVerify(platformObj.parseConfig(confJson));
            if(verifyVo.isValid()){
                renderJson(Ret.ok("message", "验证成功 "));
                return;
            }
            throw new AuthException(verifyVo.getReason());
        } catch (BaseException e){
            renderJson(Ret.fail("message", "验证失败 - " + e.getMessage()));
        } catch (Throwable e){
            renderJson(Ret.fail("message", "内部错误 - " + e.getMessage()));
        }
    }


    /**
     * 获取新版
     *
     * @return
     */
    public Properties getMasterAddonInfo(){
        Properties properties = new Properties();
        try {
            String resp = HttpUtil.httpGet("https://gitee.com/nianzecong/jpress-addon-articlesync/raw/master/src/main/resources/addon.txt");
            for(String line : resp.split("\n")){
                System.out.println(line);
                String[] val = line.split("=");
                properties.setProperty(val[0], val[1]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return properties;
    }

}
